package com.carbon.carbonmanager.service;

import com.carbon.carbonmanager.model.UserRegCodeInfo;
import com.carbon.carbonmanager.unit.RandomPassHelper;
import com.carbon.carbonmanager.unit.Response;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * 邮件服务模块
 * */
@Service
public class EmailService {

    @Autowired
    UserService userService;

    @Resource
    private JavaMailSender jms;

    /**
     * 封装邮件发送模板
     * */
    public String sendHtml(String sender, String receiver, String subject, String content) {
        MimeMessage message = jms.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //发送方
            helper.setFrom(sender);
            //接收方
            helper.setTo(receiver);
            //邮件主题
            helper.setSubject(subject);
            //邮件内容
            helper.setText(content, true);
            jms.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "邮件发送成功，请查收邮件！";
    }

    /**
     * 功能需求
     * 注册用户发送注册码，进行注册
     * @param 注册用户邮箱
     * @return 返回Response,包含随机生成的6位注册码
     * */
    public Response sendRegCode(UserRegCodeInfo userRegCodeInfo){
        //获取注册用户邮箱地址
        String user_email = userRegCodeInfo.getUser_email();

        //邮件发送者是服务邮箱
        String sender = "317834473@qq.com";
        //标题
        String subject = "碳中和管理平台注册邮件";
        //注册用户接收注册码
        String receiver = user_email;

        //随机生成6位注册码
        String reg_code = RandomPassHelper.getPassWordOne(6);
        //将随机生成的注册码装载到对象中，和注册邮箱一起添加进数据库，以备注册时校验用
        userRegCodeInfo.setReg_code(reg_code);
        //将注册用户的邮箱和生成的注册码插入数据库
        userService.resetRegCode(userRegCodeInfo);
        //邮件内容
        String content = "<html>\n" +
                "<body>\n" +
                "尊敬的用户：" +
                "<h2>这是一封注册邮件,请使用下方验证码（区分大小写）注册账号!</h2>\n" +
                "<p>提示：验证码有效时间15分钟。</p>" +
                "<p style=\"background-color: #000000;color: #ffffff;font-size: 50px;width: 300px;height: 120px;line-height: 120px;text-align: center;\">" +
                reg_code +
                "</p>"+
                "<p>注意：如果该邮件不是您操作发送，请忽视该邮件。</p>" +
                "</body>\n" +
                "</html>";
        return new Response(200,sendHtml(sender, receiver, subject, content),null);
    }

}
